package top.hepingan.java.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.hepingan.java.common.Result;
import top.hepingan.java.dto.MessageDto;
import top.hepingan.java.entity.Chat;
import top.hepingan.java.entity.ChatList;
import top.hepingan.java.entity.User;
import top.hepingan.java.mapper.ChatListMapper;
import top.hepingan.java.mapper.ChatMapper;
import top.hepingan.java.mapper.UserMapper;
import top.hepingan.java.service.ChatService;
import top.hepingan.java.utils.AliUploadUtils;
import top.hepingan.java.utils.BeanUtils;
import top.hepingan.java.utils.UserUtils;
import top.hepingan.java.vo.ChatListVo;
import top.hepingan.java.vo.ChatVo;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatMapper chatMapper;

    private final ChatListMapper chatListMapper;

    private final AliUploadUtils aliUploadUtils;
    private final UserMapper userMapper;

    /**
     * 创建/查询会话
     * @param userId
     * @return
     */
    @Override
    public Result initiate(Long userId) {
        if (Objects.equals(userId, UserUtils.getCurrentLoginId())){
            return Result.error("不能跟自己对话");
        }
        ChatList cl = chatListMapper.selectOne(new QueryWrapper<ChatList>().lambda()
                .eq(ChatList::getInitiateUserId, UserUtils.getCurrentLoginId())
                .eq(ChatList::getTargetUserId, userId));
        if (cl == null){
            ChatList chatList = new ChatList().setInitiateUserId(UserUtils.getCurrentLoginId())
                    .setTargetUserId(userId)
                    .setCreatedTime(LocalDateTime.now())
                    .setInitiateMessage(0)
                    .setLastMessage("-")
                    .setLastTime(LocalDateTime.now())
                    .setTargetMessage(0);
            chatListMapper.insert(chatList);
            return Result.data(chatList);
        }else {
            return Result.data(cl);
        }
    }

    /**
     * 发送消息
     * @param messageDto
     * @return
     */
    @Override
    public Result message(MessageDto messageDto) {
        Chat chat = new Chat().setChatListId( messageDto.getChatListId())
                .setType( messageDto.getType())
                .setContent( messageDto.getContent())
                .setUserId(UserUtils.getCurrentLoginId())
                .setCreatedTime(LocalDateTime.now());
        chatMapper.insert(chat);
        ChatList chatList = chatListMapper.selectOne(new QueryWrapper<ChatList>().lambda()
                .eq(ChatList::getId, messageDto.getChatListId()));
        //判断发送消息的用户是会话的发起者还是接收者
        if (chatList.getInitiateUserId().equals(UserUtils.getCurrentLoginId())){
            chatList.setTargetMessage(chatList.getTargetMessage()+1);
            chatList.setLastMessage(chat.getContent());
            chatList.setLastTime(LocalDateTime.now());
            chatListMapper.updateById(chatList);
        }else {
            chatList.setInitiateMessage(chatList.getInitiateMessage()+1);
            chatList.setLastMessage(chat.getContent());
            chatList.setLastTime(LocalDateTime.now());
             chatListMapper.updateById(chatList);
        }
        return Result.ok();
    }

    /**
     * 获取消息列表
     * @param chatListId
     * @return
     */
    @Override
    public Result messageList(Long chatListId,  Integer pageNum) {
        Page<Chat> page = new Page<>(pageNum, 15);
        List<Chat> chats = chatMapper.selectPage(page, new QueryWrapper<Chat>().lambda()
                .eq(Chat::getChatListId, chatListId)).getRecords();
        List<ChatVo> chatsVo = chats.stream().map(chat -> {
            ChatVo chatVo = BeanUtils.copyClassProperTies(chat, ChatVo.class);
            if (chat.getUserId().equals(UserUtils.getCurrentLoginId())){
                chatVo.setIsUser(true);
            }else {
                chatVo.setIsUser(false);
            }
            return chatVo;
        }).toList();
        return Result.data(chatsVo);
    }

    /**
     *  获取会话列表
     * @return
     */
    @Override
    public Result chatList() {
        List<ChatList> chatLists = chatListMapper.selectList(new QueryWrapper<ChatList>().lambda()
                .eq(ChatList::getInitiateUserId, UserUtils.getCurrentLoginId())
                .or()
                .eq(ChatList::getTargetUserId, UserUtils.getCurrentLoginId()));
        List<ChatListVo> chatListVos = new ArrayList<>();
        for (ChatList chatList : chatLists){
            ChatListVo chatListVo = BeanUtils.copyClassProperTies(chatList, ChatListVo.class);
            if (chatList.getInitiateUserId().equals(UserUtils.getCurrentLoginId())){
                User user = userMapper.selectOne(new QueryWrapper<User>().lambda()
                        .eq(User::getId, chatList.getTargetUserId()));
                chatListVo.setTargetUserName(user.getUsername());
                chatListVo.setTargetUserAvatar(user.getAvatar());
                chatListVo.setTargetId(chatList.getTargetUserId());
            }else if (chatList.getTargetUserId().equals(UserUtils.getCurrentLoginId())){
                User user = userMapper.selectOne(new QueryWrapper<User>().lambda()
                        .eq(User::getId, chatList.getInitiateUserId()));
                chatListVo.setTargetUserName(user.getUsername());
                chatListVo.setTargetUserAvatar(user.getAvatar());
                chatListVo.setTargetId(chatList.getInitiateUserId());
            }
            chatListVos.add(chatListVo);
        }
        return  Result.data(chatListVos);
    }


}
